package com.bclz.netty.start;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

public class NettyClientHandle extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx);
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer("Hello Server 嘻嘻!!!",CharsetUtil.UTF_8));
        /**简单的发送心跳*/
        ctx.channel().eventLoop().scheduleAtFixedRate(()->{//定时调度任务
            ctx.channel().writeAndFlush(Unpooled.copiedBuffer("发送心跳...",CharsetUtil.UTF_8));
        },2,3, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Sever[ "+ctx.channel().remoteAddress()+"] msg："+((ByteBuf)msg).toString(CharsetUtil.UTF_8));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("CLIENT HANDLE EXCEPTION...");
        ctx.close();
    }
}
